package com.example.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.enetity.User;
import com.example.mapper.UserMapper;
import com.example.service.UserService;
import com.example.utils.Md5Util;
import com.example.utils.getRedisDataUtil;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Map;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private UserMapper mapper;
    @Autowired
    private StringRedisTemplate template;




    @Override
    public User findByUsername(String username) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        return mapper.selectOne(wrapper);
    }

    @Override
    public void register(String username, String password, LocalDateTime createTime, LocalDateTime updateTime) {
        // 密码加密
        password = Md5Util.getMD5String(password);
        mapper.insert(new User(username, password, createTime, updateTime));
    }

    @Override
    public void MyUpdate(User user) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("id", user.getId());
        user.setUpdateTime(LocalDateTime.now());
        mapper.update(user, wrapper);
    }

    @Override
    public void updateAvatar(@URL String avatarUrl) {

        User user = new User();
        user.setUserPic(avatarUrl);
        user.setUpdateTime(LocalDateTime.now());
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        String s = template.opsForValue().get("data");
        JSONObject jsonObject = JSONObject.parseObject(s);
        Map<String,Object> map = (Map<String,Object>)jsonObject;
        wrapper.eq("id", map.get("id"));
        mapper.update(user, wrapper);
    }

    public void updatePassword(String password) {
        String s = template.opsForValue().get("data");
        JSONObject jsonObject = JSONObject.parseObject(s);
        Map<String,Object> map = (Map<String,Object>)jsonObject;
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("id", map.get("id"));
        User user = new User();
        user.setPassword(Md5Util.getMD5String(password));
        user.setUpdateTime(LocalDateTime.now());
        mapper.update(user, wrapper);
    }
}
